package io.renren.modules.expert.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.utils.IdDto;
import io.renren.common.utils.JsonUtils;
import io.renren.modules.answer.dto.input.QuestionAnswerInput;
import io.renren.modules.answer.dto.input.TopicInput;
import io.renren.modules.answer.dto.output.AnswerMessage;
import io.renren.modules.answer.dto.output.Message;
import io.renren.modules.answer.dto.output.Topic2;
import io.renren.modules.answer.entity.Answer;
import io.renren.modules.answer.mapper.AnswerMapper;
import io.renren.modules.expert.dto.input.SelectByQuestionIdInput;
import io.renren.modules.expert.dto.input.updateOptionInput;
import io.renren.modules.expert.dto.output.AnswerDetailOutput;
import io.renren.modules.expert.dto.output.Score;
import io.renren.modules.expert.service.ExpertReviewService;
import io.renren.modules.question.entity.QuestionMessage;
import io.renren.modules.question.mapper.QuestionMessageMapper;
import io.renren.modules.score.dao.ScoreDao;
import io.renren.modules.score.entity.ScoreEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author liangbaigao
 * @Date 2022/10/10 15:40
 */
@Service
public class ExpertReviewServiceImpl implements ExpertReviewService {


    @Resource
    private QuestionMessageMapper questionMessageMapper;

    @Resource
    private ScoreDao scoreDao;

    @Resource
    private AnswerMapper answerMapper;

    /**
     * 已发布的问卷 管理员看全部 非管理员看自己的
     *
     * @return
     */
    @Override
    public List<Message> showQuestion() {
        // 当前登录用户
        SysUserEntity principal = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<QuestionMessage> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<QuestionMessage> lambda = queryWrapper.lambda();
        lambda.eq(QuestionMessage::getState,1);
        List<QuestionMessage> questionMessageList =
                questionMessageMapper.selectList(queryWrapper);
        if (principal.getUserId() != 1) {
            lambda.eq(QuestionMessage::getCreateUser, principal.getUserId());
            questionMessageList =
                    questionMessageMapper.selectList(queryWrapper);
        }
        // 数据转化
        List<Message> messageList = new ArrayList<>();
        for (QuestionMessage questionMessage : questionMessageList) {
            Message message = new Message();
            message.setQuestionName(questionMessage.getQuestionName());
            message.setId(questionMessage.getId());
            message.setState(questionMessage.getState());
            messageList.add(message);
        }
        return messageList;
    }

    /**
     * 根据问卷id查看答卷用户 分页
     *
     * @param input
     * @return
     */
    @Override
    public Page<Score> selectByQuestionId(SelectByQuestionIdInput input) {
        // 构建分页
        Page<ScoreEntity> scorePage = new Page<>(input.getCurrPage(), input.getPageSize());
        // 根据问卷id查询答卷表
        QueryWrapper<ScoreEntity> answerQueryWrapper =
                new QueryWrapper<>();
        answerQueryWrapper.lambda().eq(ScoreEntity::getQuestionId,input.getQuestionId());
        Page<ScoreEntity> answerPage = scoreDao.selectPage(scorePage, answerQueryWrapper);
        List<Score> scores = new ArrayList<>();
        // 关系转化
        for (ScoreEntity record : answerPage.getRecords()) {
            Score score = new Score();
            score.setResponse(record.getResponse());
            score.setAnswerId(record.getAnswerId());
            scores.add(score);
        }
        Page<Score> scorePage1 = new Page<>(answerPage.getCurrent(),answerPage.getSize(),answerPage.getTotal());
        scorePage1.setRecords(scores);
        return scorePage1;
    }

    /**
     * 根据根据答卷id查该用户的答卷详情
     *
     * @param id
     * @return
     */
    @Override
    public AnswerDetailOutput selectByAnswerId(IdDto id) {
        AnswerDetailOutput answerDetailOutput =
                new AnswerDetailOutput();
        // 根据答卷id查询答卷表
        Answer answer = answerMapper.selectById(id);
        QuestionAnswerInput questionAnswerInput =
                JsonUtils.jsonToPojo(answer.getAnswerDetail(),QuestionAnswerInput.class);
        AnswerMessage answerMessage = new AnswerMessage();
        // 答卷id
        answerMessage.setId(answer.getId());
        // 答卷名称
        assert questionAnswerInput != null;
        answerMessage.setQuestionName(questionAnswerInput.getQuestionName());
        answerDetailOutput.setAnswerMessage(answerMessage);
        // 转换数据
        List<Topic2> topic2s = new ArrayList<>();
        List<TopicInput> questionTopics = questionAnswerInput.getQuestionTopics();
        for (TopicInput questionTopic : questionTopics) {
            Topic2 topic2 = new Topic2();
            topic2.setTopicId(questionTopic.getTopicId());
            topic2.setTopicName(questionTopic.getTopicName());
            topic2.setIsPdf(questionTopic.getIsPdf());
            topic2.setOption(questionTopic.getOption());
            topic2.setTopicNumber(questionTopic.getTopicNumber());
            topic2s.add(topic2);
        }
        // 试卷总分
        QueryWrapper<ScoreEntity> scoreEntityQueryWrapper =
                new QueryWrapper<>();
        scoreEntityQueryWrapper.lambda().eq(ScoreEntity::getAnswerId,id.getId());
        List<ScoreEntity> scoreEntities =
                scoreDao.selectList(scoreEntityQueryWrapper);
        for (ScoreEntity scoreEntity : scoreEntities) {
            answerDetailOutput.setTotalScore(scoreEntity.getScore());
        }
        answerDetailOutput.setTopic(topic2s);
        return answerDetailOutput;
    }

    /**
     * 专家更改选项分
     * @param input
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateByOptionId(List<updateOptionInput> input) {
//        // 根据答卷id查询答卷表
//        Answer answer = answerMapper.selectById(input.getAnswerId());
//        QuestionAnswerInput questionAnswerInput =
//                JsonUtils.jsonToPojo(answer.getAnswerDetail(),QuestionAnswerInput.class);
//        List<TopicInput> questionTopics = new ArrayList<>();
//        List<OptionTwo> optionTwos = new ArrayList<>();
//        // 更改答题详情
//        assert questionAnswerInput != null;
//        for (TopicInput questionTopic : questionAnswerInput.getQuestionTopics()) {
//            for (OptionTwo optionTwo : questionTopic.getOption()) {
//                if(optionTwo.getOptionId().equals(input.getOptionId())){
//                    optionTwo.setOptionScore(input.getNewScore());
//                }
//                optionTwos.add(optionTwo);
//            }
//            questionTopic.setOption(optionTwos);
//            questionTopics.add(questionTopic);
//        }
//        questionAnswerInput.setQuestionTopics(questionTopics);
//        answer.setAnswerDetail(JsonUtils.objectToJson(questionAnswerInput));
//        // 重新入库
//        answerMapper.updateById(answer);
        // 根据问卷id修改总分 选中就改总分 ，没选中就不改
        for (updateOptionInput updateOptionInput : input) {
            if("1".equals(updateOptionInput.getIsChecked())){
                QueryWrapper<ScoreEntity> scoreEntityQueryWrapper =
                        new QueryWrapper<>();
                scoreEntityQueryWrapper.lambda().
                        eq(ScoreEntity::getAnswerId,updateOptionInput.getAnswerId());
                List<ScoreEntity> scoreEntities =
                        scoreDao.selectList(scoreEntityQueryWrapper);
                // 总分减去旧的分值 在去加上新的分值
                for (ScoreEntity scoreEntity : scoreEntities) {
                    if(ObjectUtil.isNull(scoreEntity.getNewScore())){
                        scoreEntity.setNewScore(scoreEntity.getScore()
                                -updateOptionInput.getOldScore()+ updateOptionInput.getNewScore());
                    }else {
                        scoreEntity.setNewScore(scoreEntity.getNewScore()
                                -updateOptionInput.getOldScore()+ updateOptionInput.getNewScore());
                    }
                    scoreDao.updateById(scoreEntity);
                }
            }
        }
    }
}
